<template>
  <div class="manager">
    <el-card class="el-card">
      <el-row :gutter="30">
        <el-col :span="8">
          <el-input v-model="keyword" placeholder="请输入管理员" clearable>
            <template #append>
              <el-button :icon="Search" @click="getDataList"/>
            </template>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="addManagerHandle"
            >新增管理员</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="tableData" style="width: 100%" class="el-table">
        <el-table-column prop="date" label="管理员" width="180">
          <template #default="scope">
            <div class="avatar">
              <el-avatar
                :size="50"
                :src="scope.row.avatar"
                class="el-avatar"
              ></el-avatar>
              {{ scope.row.username }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="所属管理员" width="180">
          <template #default="scope">
            <div>
              {{ scope.row.role.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="状态">
          <template #default="scope">
            <div>
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="changeState(scope.row)"
              ></el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template #default="scope">
            <div>
              <el-button
                type="primary"
                :icon="Edit"
                size="small"
                @click="editMansgerHandle(scope.row)"
              ></el-button>
              <el-button
                type="warning"
                :icon="Delete"
                size="small"
                @click="delMansgerHandle(scope.row.id)"
              ></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="el-pagination" v-model:current-page="page" v-model:page-size="limit" :page-sizes="[5, 10, 15, 20]"
            :small="small" :background="background" layout="total, sizes, prev, pager, next, jumper" :total=total
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>
    <!-- 新增管理员弹框 -->
    <el-dialog
      v-model="dialogVisibleAddManager"
      :title="dialogTtile"
      @close="closeAddDialogHandle"
      width="40%"
    >
      <el-form
        ref="ruleFormRefAddManager"
        :model="ruleFormAddManager"
        :rules="rulesAddManager"
        label-width="105px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="ruleFormAddManager.username"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="ruleFormAddManager.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属角色" prop="role_id">
          <el-select
            v-model="ruleFormAddManager.role_id"
            placeholder="请选择角色"
            class="select-width"
          >
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <SelectImg v-model="ruleFormAddManager.avatar"></SelectImg>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="ruleFormAddManager.status"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisibleAddManager = false">取消</el-button>
          <el-button type="primary" @click="addManagerOkHandle">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { Search, Delete, Edit } from "@element-plus/icons-vue";
import { getManagerList, editState } from "@/api/manager.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { addManager, delManager, editManager } from "@/api/manager.js";
const keyword = ref("");
const tableData = ref([]);
// 开启分页背景
const background = ref('background')
// 分页页码
const page = ref(1);
// 分页条数
const limit = ref(5);
// 总条数
const total = ref(0);
// 新增管理员弹框显示与隐藏
const dialogVisibleAddManager = ref(false);
// 弹框标题
const dialogTtile = ref("");
// 弹框实例
const ruleFormRefAddManager = ref(null);
// 弹框数据源
const ruleFormAddManager = ref({
  username: "",
  password: "",
  role_id: "",
  status: 1,
  avatar: "",
});

// 弹框校验规则
const rulesAddManager = ref({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  role_id: [{ required: true, message: "请选择所属角色", trigger: "blur" }],
});
// 所属角色下拉数据
const rolesList = ref([]);
// 获取管理员数据
const getDataList = async () => {
  const res = await getManagerList(page.value, limit.value, keyword.value);
  if (res.msg && res.msg !== "ok") {
    ElMessage.error(res.msg);
  }
  tableData.value = res.data.list;
  rolesList.value = res.data.roles;
  total.value = res.data.totalCount
};
getDataList();
// 修改状态
const changeState = async (row) => {
  const res = await editState(row.id, row.status);
  if (res.msg && res.msg !== "ok") return;
  ElMessage({
    message: "修改成功",
    type: "success",
  });
  getDataList();
};
// 打开新增管理员对话框
const addManagerHandle = () => {
  dialogTtile.value = "新增管理员";
  dialogVisibleAddManager.value = true;
};
const managerId = ref("");
// 编辑打开管理员对话框
const editMansgerHandle = (row) => {
  console.log(row, "row");
  dialogTtile.value = "编辑管理员";
  ruleFormAddManager.value.username = row.username;
  ruleFormAddManager.value.role_id = row.role_id;
  ruleFormAddManager.value.password = row.password;
  ruleFormAddManager.value.status = row.status;
  ruleFormAddManager.value.avatar = row.avatar;
  managerId.value = row.id;
  dialogVisibleAddManager.value = true;
};
// 关闭弹框
const closeAddDialogHandle = () => {
  ruleFormRefAddManager.value.resetFields();
};
// 新增管理员确认
const addManagerOkHandle = () => {
  // 校验表单
  ruleFormRefAddManager.value.validate(async (isValid) => {
    if (!isValid) return;
    // 调用新增Api
    if (dialogTtile.value == "新增管理员") {
      const res = await addManager(ruleFormAddManager.value);
      if (res.msg && res.msg !== "ok") return;
      ElMessage.success("新增成功");
    } else {
      const res = await editManager(managerId.value, ruleFormAddManager.value);
      if (res.msg && res.msg !== "ok") return;
      ElMessage.success("修改成功");
    }
    // 关闭对话框
    dialogVisibleAddManager.value = false;
    getDataList();
  });
};
// 删除管理员
const delMansgerHandle = async (id) => {
  const isdel = await ElMessageBox.confirm("是否删除", "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).catch((err) => {
    console.log(err);
  });
  if (isdel == "confirm") {
    const res = await delManager(id);
    if (res.msg && res.msg !== "ok") return;
    ElMessage.success("删除成功");
    getDataList();
  }
};
// 
const handleSizeChange = (val) => {
    limit.value = val
    getDataList()
}
const handleCurrentChange = (val) => {
    page.value = val
    getDataList()
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 20px;
}
.el-table {
  margin-top: 20px;
}
.avatar {
  display: flex;
  align-items: center;
  .el-avatar {
    margin-right: 15px;
  }
}
.el-pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50px;
    margin-top: 20px;
    // margin: 10px auto;
}
</style>
